package com.chenken;

import java.text.DecimalFormat;

public abstract class Sort<T extends Comparable<T>> implements Comparable<Sort<T>>{

	protected T[] arrays;
	
	/**
	 * 耗时
	 */
	private long time;
	
	/**
	 * 比较次数
	 */
	private int cmpCount;
	
	/**
	 * 交换次数
	 */
	private int swapCount;
	
	private DecimalFormat fmt = new DecimalFormat("#.00");
	
	public void sort(T[] arrays) {
		if(arrays == null || arrays.length < 2) {
			return;
		}
		this.arrays = arrays;
		long startTime = System.currentTimeMillis();
		sort();
		long endTime = System.currentTimeMillis();
		time = endTime-startTime;
	}

	protected abstract void sort();

	@Override
	public int compareTo(Sort<T> o) {
		return (int)(time - o.time);
	}
	
	protected void swap(int index1,int index2) {
		T temp = arrays[index1];
		arrays[index1] = arrays[index2];
		arrays[index2] = temp;
		swapCount++;
	}

	protected int compare(T o1,T o2) {
		cmpCount++;
		return o1.compareTo(o2);
	}

	@Override
	public String toString() {
		String timeStr = "耗时：" + (time / 1000.0) + "s(" + time + "ms)";
		String compareCountStr = "比较：" + numberString(cmpCount);
		String swapCountStr = "交换：" + numberString(swapCount);
		//String stableStr = "稳定性：" + isStable();
		return "【" + getClass().getSimpleName() + "】\n" 
				//+ stableStr + " \t"
				+ timeStr + " \t"
				+ compareCountStr + "\t "
				+ swapCountStr + "\n"
				+ "------------------------------------------------------------------";
	}
	
	private String numberString(int number) {
		if (number < 10000) return "" + number+"次";
		
		if (number < 100000000) return fmt.format(number / 10000.0) + "万次";
		return fmt.format(number / 100000000.0) + "亿次";
	}
}
